{% extends 'common_project_tpl.html' %}
{% load static %}
{% block css %}
    <style>
        .panel-default .panel-heading .panel-title {
        {# 弹性盒子，指定主轴方向为行对齐，对齐方式，两端对齐#} display: flex;
            flex-direction: row;
            justify-content: space-between;
        }

        .panel-default a {
            text-decoration: none;
        }

        .panel-default > .panel-heading .function .upload {
            overflow: hidden; /* 隐藏溢出的内容，使内容作为btn-xs大小固定 */
        }

        .panel-default > .panel-heading .function .upload input {
            opacity: 0;
            position: absolute;
            top: 0;
            bottom: 0;
            width: 76px;
            left: -2px;
            overflow: hidden;
        }

        .upload-progress {
            position: fixed;
            right: 2px;
            bottom: 2px;
            width: 400px;
        }

        .upload-progress .progress-error {
            color: red;
        }
    </style>
{% endblock %}
{% block content %}

    <div class="container-fluid" style="margin-top: 20px">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h3 class="panel-title">
                    <div>
                        <a href="{% url 'main:file' pro_id %}"><i class="fa fa-home" aria-hidden="true"/></i> 文件库</a>
                        {% if path_list %}
                            {% for path in path_list %}
                                <span>></span>
                                <a href="{% url 'main:file' pro_id %}?folder_id={{ path.id }}"> {{ path.name }}</a>
                            {% endfor %}
                        {% endif %}
                    </div>
                    <div class="function">
                        <a href="#" id="show-upload" class="btn btn-info btn-xs"><i class="fa fa-sellsy"
                                                                                    aria-hidden="true"/></i> 显示上传进度</a>
                        <!-- Button trigger modal -->
                        <div class="btn btn-primary btn-xs upload" style="position: relative">
                            <div><i class="fa fa-upload" aria-hidden="true"></i> 上传文件</div>
                            <input type="file" multiple name="uploadFile" id="uploadFile">
                        </div>

                        <a href="#" class="btn btn-success btn-xs" data-toggle="modal" data-target="#file-Modal"
                           data-name="新建文件夹">
                            <i class="fa fa-plus-circle" aria-hidden="true"/></i> 新建文件夹
                        </a>

                        <!-- Modal -->
                        <div class="modal fade" id="file-Modal" tabindex="-1" role="dialog"
                             aria-labelledby="myModalLabel">
                            <div class="modal-dialog" role="document">
                                <div class="modal-content">
                                    <div class="modal-header">
                                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                            <span aria-hidden="true">&times;</span></button>
                                        <h4 class="modal-title" id="myModalLabel"></h4>
                                    </div>
                                    <div class="modal-body">
                                        <form id="file-form">
                                            {% csrf_token %}
                                            <div class="form-group">
                                                <label for="folder-name">名称</label>
                                                <input type="text" class="form-control" id="folder-name" name="name"
                                                       placeholder="请输入文件夹名">
                                                <span class="error-msg"></span>
                                            </div>
                                        </form>
                                    </div>
                                    {#                                    <span id="non_field_errors" class="error-msg"></span>#}
                                    <div class="modal-footer">
                                        <button type="button" class="btn btn-default" data-dismiss="modal">关闭
                                        </button>
                                        <button id="form-submit" type="button" class="btn btn-primary">保存</button>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Modal-alter -->
                        <div class="modal fade" id="file-Modal-alert" tabindex="-1" role="dialog"
                             aria-labelledby="myModalLabel">
                            <div class="modal-dialog" role="document">
                                <div class="alert alert-danger alert-dismissible fade in" role="alert">
                                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                                            aria-hidden="true">×</span></button>
                                    <h4>确定要进行删除吗？</h4>
                                    <p>删除操作将不可找回，如果删除文件夹会一并删除其内部的所有子文件和子文件夹</p>
                                    <p style="text-align: right">
                                        <button id="delete" type="button" class="btn btn-danger">确认删除</button>
                                        <button type="button" class="btn btn-default" data-dismiss="modal">
                                            关闭
                                        </button>
                                    </p>
                                    <span class="error-msg"></span>
                                </div>
                            </div>
                        </div>

                    </div>
                </h3>
            </div>
            <div class="panel-body">
                <table class="table">
                    {#                    <caption>Optional table caption.</caption>#}
                    <thead>
                    <tr>
                        <th>名称</th>
                        <th>文件大小</th>
                        <th>更新者</th>
                        <th>更新时间</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody id="show-file-list">


                    </tbody>
                </table>
            </div>
        </div>
    </div>
    <div id="uploadProgress" class="upload-progress hide">
        <div class="panel panel-warning">
            <div class="panel-heading" style="display: flex; flex-direction: row;justify-content: space-between;">
                <div><i class="fa fa-cloud-upload" aria-hidden="true"></i> 上传进度</div>
                <a id='hide-upload' href="#">x</a>
            </div>

            <table class="table">
                <tbody id="progressList">
                <tr>
                    <td>

                    </td>
                </tr>
                </tbody>
            </table>
        </div>
    </div>
    <div id="uploadprogresstpl" class="hide">
        <tr>
            <td>
                <div class="name">lala</div>
                <div class="progress">
                    <div class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0"
                         aria-valuemax="100" style="width: 60%;">
                        60%
                    </div>
                </div>
                <div class="progress-error"></div>
            </td>
        </tr>
    </div>


{% endblock %}
{% block js %}
    <script src="{% static 'js/cos-js-sdk-v5.min.js' %}"></script>
    <script>
        var FILE_VIEWSET_URL = "{% url 'main:file-list' %}"
        var FILE_VIEWSET_SIGLE_URL = "{% url 'main:file-detail' folder_id %}"
        var COS_CREDENTIAL = "{% url 'main:api_file_credential' pro_id %}"
        var FIlE_CHECK = "{% url 'main:api_file_check' pro_id %}"
        var COS_OBJECT = new COS({
            getAuthorization: function (options, callback) {
                $.get({
                    url: COS_CREDENTIAL,
                    dataType: 'json',
                    headers: {
                        'X-CSRFTOKEN': $("[name='csrfmiddlewaretoken']").val()
                    },
                    success: function (res) {
                        if (res.ret === 0) {
                            var credentials = res.data && res.data.credentials;
                            callback({
                                TmpSecretId: credentials.tmpSecretId,
                                TmpSecretKey: credentials.tmpSecretKey,
                                XCosSecurityToken: credentials.sessionToken,
                                StartTime: res.data.startTime,
                                ExpiredTime: res.data.expiredTime
                            });
                        } else {
                            alert(res.error);
                        }
                    },
                    error: function (res) {
                        alert(res.responseJSON.errors)
                    }
                });
            }
        });
        $(function () {
            initModal();
            addFolder();
            showFiles();
            bindUploadFile();
            hideUpload();
            showUpload();
        })

        function initModal() {
            $('#file-Modal').on('show.bs.modal', function (event) { // 当模态框显示时，会自动触发此函数
                let button = $(event.relatedTarget) // 事件触发的jquery对象
                let recipient = button.data('name') //获取该对象的data-*属性
                let old_name = button.data('old_name')
                let fid = button.data('fid')
                let type = button.data('type')
                let modal = $(this) // this指向模态对话框本身
                modal.find('.modal-title').text(recipient)
                if (fid) {
                    modal.find('#folder-name').val(old_name)
                    modal.find('#form-submit').attr('fid', fid)
                    modal.find('#form-submit').attr('ftype', type)
                } else {
                    modal.find('#form-submit').removeAttr('fid')
                    $('#file-form')[0].reset();  // 利用dom对象重置表单数据
                }
                $('.error-msg').empty();
            })
        }

        function addFolder() {
            $('#form-submit').click(function () {
                console.log()
                if ($(this).attr('fid')) {
                    modifyFolderOrFile($(this).attr('fid'), $(this).attr('ftype'));
                    return;
                }
                $('.error-msg').empty();
                {#收集已经输入的表单数据#}
                let data = {};
                let form_data = $('#file-form').serializeArray()
                $.each(form_data, function () {
                    data[this.name] = this.value; // 这里this对象，指代遍历form_data中每个元素对象
                });
                data['project'] = {{ pro_id }};
                data['file_type'] = 2;
                data['update_user'] = {{ request.user.id }};
                {% if folder_id %}
                    data['parent'] = {{ folder_id }};
                {% else %}
                    data['parent'] = null;
                {% endif %}
                $.ajax({
                    url: FILE_VIEWSET_URL,
                    type: "post",
                    data: data,
                    dataType: "JSON",
                    success: function (res) {
                        if (res.ret === 0) {
                            location.reload();
                        } else { //循环此字典每次循环执行函数
                            $.each(res.errors, function (name, data) {
                                $('#folder-name').next().text(data[0])
                            })
                        }
                    }
                })

            })

        }

        function showFiles() {
            $.ajax({
                url: FILE_VIEWSET_URL,
                type: 'get',
                data: {
                    {% if folder_id %}
                        'folder_id':{{ folder_id }},
                    {% endif %}
                    'project':{{ pro_id }}
                },
                dataType: 'json',
                success: function (res) {
                    if (res.ret === 0) {
                        $.each(res.data, function (index, item) {
                            if (item.file_type === 2) {
                                let folder_url = "{% url 'main:file' pro_id %}?folder_id=" + item.id.toString()
                                var htmlCode = `
                                    <tr>
                                        <td>
                                             <a href="${folder_url}"><i class="fa fa-folder" aria-hidden="true"/></i> ${item.name}</a>
                                        </td>
                                        <td>-</td>
                                        <td>${item.update_user_name}</td>
                                        <td>${item.update_datetime}</td>
                                        <td>
                                            <a href="#" class="btn btn-primary btn-xs" data-fid='${item.id}' data-type='${item.file_type}' data-toggle="modal" data-target="#file-Modal"
                           data-name="编辑文件夹" data-old_name="${item.name}">编辑</a>
                                            <a href="#" class="btn btn-danger btn-xs folder_delete" data-toggle="modal" data-target="#file-Modal-alert" fid="${item.id}">删除</a>
                                        </td>
                                    </tr>`
                            } else {
                                var htmlCode = `
                                    <tr>
                                        <td><i class="fa fa-file" aria-hidden="true"/></i> ${item.name}</td>
                                        <td>${(item.file_size / 1024 / 1024).toFixed(2)}M</td>
                                        <td>${item.update_user_name}</td>
                                        <td>${item.update_datetime}</td>
                                        <td>
                                            <a href="#" class="btn btn-primary btn-xs" data-fid='${item.id}' data-type='${item.file_type}' data-toggle="modal" data-target="#file-Modal"
                           data-name="编辑文件名" data-old_name="${item.name}">编辑</a>
                                            <a href="#" class="btn btn-danger btn-xs folder_delete" data-toggle="modal" data-target="#file-Modal-alert" fid="${item.id}">删除</a>
                                            <a href="#" class="btn btn-success btn-xs download-file-btn" key="${item.key}" filename="${item.name}">下载</a>
                                        </td>
                                    </tr>`
                            }
                            $('#show-file-list').append(htmlCode)
                        })
                    } else {
                        alert('数据加载失败');
                    }
                    deleteFolder();
                    downloadFile();
                }
            })
        }

        function modifyFolderOrFile(fid, ftype) {
            let data = {};
            let form_data = $('#file-form').serializeArray()
            $.each(form_data, function () {
                data[this.name] = this.value; // 这里this对象，指代遍历form_data中每个元素对象
            });
            let modify_url = "{% url 'main:file-detail' pk=1 %}".replace('/1', `/${fid}`)
            data['project'] = {{ pro_id }};
            data['file_type'] = ftype;
            data['update_user'] = {{ request.user.id }};
            $.ajax({
                url: modify_url,
                data: data,
                dataType: 'json',
                type: 'put',
                headers: {
                    'X-CSRFTOKEN': $("[name='csrfmiddlewaretoken']").val()
                },
                success: function (res) {
                    if (res.ret === 0) {
                        location.reload();
                    } else { //循环此字典每次循环执行函数
                        $.each(res.errors, function (name, data) {
                            $('#folder-name').next().text(data[0])
                        })
                    }
                }
            })
        }

        function deleteFolder() {
            let doc = $('.folder_delete')
            doc.unbind('click')
            doc.click(function () {
                let fid = $(this).attr('fid')
                let modify_url = "{% url 'main:file-detail' pk=1 %}".replace('/1', `/${fid}`)
                $("#delete").click(function () {
                    $.ajax({
                        url: modify_url,
                        data: {
                            'project':{{ pro_id }}
                        },
                        dataType: 'json',
                        type: 'delete',
                        headers: {
                            'X-CSRFTOKEN': $("[name='csrfmiddlewaretoken']").val()
                        },
                        success: function (res) {
                            if (res.ret === 0) {
                                location.reload();
                            } else { //循环此字典每次循环执行函数
                                $.each(res.errors, function (name, data) {
                                    $('#folder-name').next().text(data[0])
                                })
                            }
                        }
                    })
                })
            })
        }

        function bindUploadFile() {
            $('#uploadFile').change(function () {
                var fileList = $(this)[0].files;
                // 获取本次要上传的每个文件 名称&大小
                var checkFileList = [];
                $.each(fileList, function (index, fileObject) {
                    let file_info = {
                        'name': fileObject.name,
                        'size': fileObject.size,
                        'project':{{ pro_id }}
                    }
                    {% if folder_id %}
                        file_info['parent'] = {{ folder_id }};
                    {% else %}
                        file_info['parent'] = null;
                    {% endif %}
                    checkFileList.push(file_info)
                })
                $("#progressList").empty();
                $.ajax({
                    url: FIlE_CHECK,
                    data: JSON.stringify(checkFileList),
                    dataType: 'json',
                    type: 'post',
                    headers: {
                        'X-CSRFTOKEN': $("[name='csrfmiddlewaretoken']").val()
                    },
                    success: function (res) {
                        if (res.ret === 0) {
                            $('#uploadProgress').removeClass('hide');
                            console.log(fileList)
                            $.each(fileList, function (index, fileObject) {
                                let htmlCode = `
                                    <tr>
                                        <td>
                                            <div class="name">${fileObject.name}</div>
                                            <div class="progress">
                                                <div id="file_${index}" class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0"
                                                     aria-valuemax="100" style="width: 0%;">
                                                    0%
                                                </div>
                                            </div>
                                            <div class="progress-error"></div>
                                        </td>
                                    </tr>`
                                $('#progressList').append(htmlCode);
                                let key = fileRename(fileObject.name);
                                COS_OBJECT.putObject({
                                    Bucket: "{{ request.tracer.project.bucket }}", /* 填入您自己的存储桶，必须字段 */
                                    Region: "{{ request.tracer.project.region }}",  /* 存储桶所在地域，例如ap-beijing，必须字段 */
                                    Key: key,  /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
                                    Body: fileObject, /* 必须，上传文件对象，可以是input[type="file"]标签选择本地文件后得到的file对象 */
                                    onProgress: function (progressData) {
                                        console.log(JSON.stringify(progressData));
                                        let percent_value = progressData.percent * 100 + '%'
                                        console.log($("#" + "file_" + index))
                                        $("#" + "file_" + index).text(percent_value);
                                        $("#" + "file_" + index).css('width', percent_value);
                                    }
                                }, function (err, data) {
                                    console.log(err || data);
                                    if (data && data.statusCode === 200) {
                                        let my_data = {
                                            project:{{ pro_id }},
                                            file_type: 1,
                                            file_size: fileObject.size,
                                            update_user:{{ request.user.id }},
                                            name: fileObject.name,
                                            file_path: data.Location,
                                            etag: data.ETag
                                        };
                                        my_data.key = key
                                        {% if folder_id %}
                                            my_data['parent'] = {{ folder_id }};
                                        {% else %}
                                            my_data['parent'] = null;
                                        {% endif %}
                                        addFile(my_data);
                                    } else {
                                        alert(err || data);
                                    }
                                    $('#uploadFile').val('')
                                });
                            })
                        }
                    },
                    error: function (res) {
                        alert(res.responseJSON.errors)
                    }
                })
            });
        }

        function addFile(data) {
            $.ajax({
                url: FILE_VIEWSET_URL,
                type: 'post',
                dataType: 'json',
                data: data,
                headers: {
                    'X-CSRFTOKEN': $("[name='csrfmiddlewaretoken']").val()
                },
                success: function (res) {
                    console.log(res)
                    {#location.reload()#}
                    if (res.ret === 0) {
                        let item = res.data
                        var htmlCode = `
                                    <tr>
                                        <td><i class="fa fa-file" aria-hidden="true"/></i> ${item.name}</td>
                                        <td>${(item.file_size / 1024 / 1024).toFixed(2)}M</td>
                                        <td>${item.update_user_name}</td>
                                        <td>${item.update_datetime}</td>
                                        <td>
                                            <a href="#" class="btn btn-primary btn-xs" data-fid='${item.id}' data-type='${item.file_type}' data-toggle="modal" data-target="#file-Modal"
                           data-name="编辑文件名" data-old_name="${item.name}">编辑</a>
                                            <a href="#" class="btn btn-danger btn-xs folder_delete" data-toggle="modal" data-target="#file-Modal-alert" fid="${item.id}">删除</a>
                                            <a href="#" class="btn btn-success btn-xs download-file-btn" key="${item.key}" filename="${item.name}">下载</a>
                                        </td>
                                    </tr>`
                        $('#show-file-list').append(htmlCode);
                    } else {
                        alert(res.errors.non_field_errors[0]);
                        // 补充阻止上传
                    }
                    downloadFile();
                    deleteFolder();
                }
            })
        }

        function fileRename(fname) {
            return {{ request.user.mobile }}+'_' + (new Date()).getTime() + "_" + fname
        }

        function hideUpload() {
            $('#hide-upload').click(function () {
                $('#uploadProgress').addClass('hide');
            })
        }

        function showUpload() {
            $('#show-upload').click(function () {
                $('#uploadProgress').removeClass('hide');
            })
        }

        function downloadFile() {
            let doc = $(".download-file-btn")
            doc.unbind('click')
            doc.click(function () {
                let key = $(this).attr('key');
                let filename = $(this).attr('filename')
                COS_OBJECT.getObjectUrl({
                    Bucket: "{{ request.tracer.project.bucket }}", /* 填写自己的 bucket，必须字段 */
                    Region: "{{ request.tracer.project.region }}",     /* 存储桶所在地域，必须字段 */
                    Key: key,              /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
                }, function (err, data) {
                    if (err) return console.log(err);
                    /* 通过指定 response-content-disposition=attachment 实现强制下载 */
                    var downloadUrl = data.Url + (data.Url.indexOf('?') > -1 ? '&' : '?') + 'response-content-disposition=attachment';
                    /* 可拼接 filename 来实现下载时重命名 */
                    /* downloadUrl += ';filename=myname'; */
                    downloadUrl += ';filename=' + filename
                    // （推荐使用 window.open()方式）这里是新窗口打开 url，如果需要在当前窗口打开，可以使用隐藏的 iframe 下载，或使用 a 标签 download 属性协助下载
                    window.open(downloadUrl);
                    // 创建一个隐藏的下载链接(以下为使用a标签download属性协助下载)
                    {#var downloadLink = document.createElement("a");#}
                    {#downloadLink.setAttribute("href", downloadUrl);#}
                    {#downloadLink.setAttribute("download", '123.jpg');#}
                    {#downloadLink.style.display = "none";#}
                    {#document.body.appendChild(downloadLink);#}
                    {#// 触发点击事件，弹出文件保存对话框#}
                    {#downloadLink.click();#}
                    {#// 删除隐藏链接#}
                    {#document.body.removeChild(downloadLink);#}
                });

            })
        }

    </script>
{% endblock %}
